package com.starhub.common.security.util;

import com.alibaba.fastjson.JSON;
import com.starhub.common.sys.user.LoginUser;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 *  自定义工具类（全局通用） 获取当前登录用户基本信息
 */
public class SecurityUtils {

    private static final Logger log = LoggerFactory.getLogger(SecurityUtils.class);

    public static LoginUser getCurrentUser() {

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return null;
            }
            Object principal = authentication.getPrincipal();
            if (principal instanceof LoginUser) {
                return (LoginUser) principal;
            } else if (principal instanceof String) {
                // 如果存储的是 JSON 字符串，反序列化回对象
                return JSON.parseObject((String) principal, LoginUser.class);
            }
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 获取当前用户ID
     * @return 用户ID 或 null（未登录时）
     */
    public static String getCurrentUserId() {
        LoginUser user = getCurrentUser();
        return user != null ? user.getUserId() : null;
    }

}

